<?php
namespace WDB\Query\Element;
use WDB;
/**
 * Field selected by SELECT consiting of expression and optionally alias
 *
 * @author Richard Ejem <richard(at)ejem.cz>
 * @package WDB
 * 
 * @property iExpression $expression
 * @property string alias
 */
class SelectField extends WDB\BaseObject{
    /**@var iExpression*/
    protected $expr;
    /**@var string|NULL*/
    protected $alias;
    
    public function __construct($expr, $alias = NULL)
    {
        $this->setExpression($expr);
        $this->alias = $alias;
    }
    
    /**@param iExpression|string $expr */
    public function setExpression($expr)
    {
        if ($expr instanceof \WDB\Query\Element\iExpression)
        {
            $this->expr = $expr;
        }
        else
        {
            $this->expr = ColumnIdentifier::create($expr);
        }
    }
    
    /**@return ColumnIdentifier|NULL */
    public function getColumnIdentifier()
    {
        if ($this->expr instanceof ColumnIdentifier)
            return $this->expr;
        return NULL;
    }
    
    /**@return iExpression */
    public function getExpression()
    {
        return $this->expr;
    }
    
    /**@param string alias */
    public function setAlias($alias)
    {
        $this->alias = $alias === NULL ? NULL : (string)$alias;
    }
    
    /**@return string*/
    public function getAlias()
    {
        return $this->alias;
    }
    
    /**
     * Return identifier by which this column is identified in result set (alias if present, or column name if not)
     *
     * @return string
     */
    public function getIdentifier()
    {
        if ($this->getAlias()) return $this->alias;
        if ($this->getColumnIdentifier()) return $this->getColumnIdentifier()->column;
        return NULL; //non-column and non-aliased select field has no deterministic identifier
    }
    
}